package com.lh.fruit.controllers;

import com.lh.fruit.dao.FruitDAO;
import com.lh.fruit.dao.impl.FruitDAOImpl;
import com.lh.fruit.pojo.Fruit;
import com.lh.fruit.service.FruitService;
import com.lh.fruit.service.impl.FruitServiceIpml;
import com.lh.myssm.myspringmvc.ViewBaseServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class FruitController {
    private FruitService fruitService = null;

    public String getList(HttpServletRequest req, String oper, Integer pageNo, String keyword) {

        String pageSize = "5";
        Integer pageCount;
        List<Fruit> fruitList;
        HttpSession session = req.getSession();

        if (pageNo == null) pageNo = 1;

        if (oper == null) {
            Object keywordObj = session.getAttribute("keyword");

            if (keywordObj != null) {
                keyword = (String) keywordObj;
            } else keyword = "";
        } else {
            pageNo = 1;
            if (keyword == null) keyword = "";

            session.setAttribute("keyword", keyword);
        }

        pageCount = fruitService.getCountByQuery(keyword);
        fruitList = fruitService.getFruitByQuery(keyword, pageNo, pageSize);

        session.setAttribute("fruitList", fruitList);
        pageCount = (pageCount + Integer.parseInt(pageSize) - 1) / Integer.parseInt(pageSize);
        session.setAttribute("pageCount", pageCount);
        session.setAttribute("pageNo", pageNo);

        return "index";
    }

    public String edit(HttpServletRequest req, Integer fid) {
        Fruit fruit = fruitService.getFruitByFid(fid);
        if (fruit == null) {
            return "error";
        }
        req.setAttribute("fruit", fruit);
        return "edit";
    }

    public String update(Integer fid, String fname, Integer price, Integer fcount, String remark) {
        fruitService.updateByFid(new Fruit(fid, fname, price, fcount, remark));
        return "redi:Fruit.do";
    }

    public String del(Integer fid) {
        if (fid == null) {
            return "error";
        }
        fruitService.delByFid(fid);
        return "redi:Fruit.do";
    }

    public String add(String fname, Integer price, Integer fcount, String remark) {
        Fruit fruit = new Fruit(0, fname, price, fcount, remark);
        fruitService.add(fruit);
        return "redi:Fruit.do";
    }
}
